package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.BlogDao;
import model.Blog;
import model.User;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    //对于Dao，也就是对数据库操作的对象我们通常把他们提出来（别的同理）
    BlogDao blogDao = new BlogDao();
    //ctrl + o
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        resp.setContentType("application/json;charset=utf-8");
        String result;
        //如果存在参数blogId，则返回博客详情，否则返回博客列表
        String blogIdParam = req.getParameter("blogId");
        if(blogIdParam == null || "".equals(blogIdParam)){
            //博客列表
            //获取所有的博客列表
            List<Blog> blogs = blogDao.selectAll();
            //转换为JSON串
            result = JSONUtil.toJson(blogs);
        }else{
            //博客详情页
            Integer blogId = Integer.parseInt(blogIdParam);
            Blog blog = blogDao.selectById(blogId);
            result = JSONUtil.toJson(blog);
        }
        //先设置编码，再返回结果
        resp.getWriter().write(result);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || "".equals(title) || content == null || "".equals(content)){
            resp.getWriter().write("标题或者内容为空");
            return;
        }
        //插入博客 需要拿到作者（登录用户），标题，内容
        HttpSession session = req.getSession(false);
        if(session == null || session.getAttribute("user") == null){
            resp.getWriter().write("用户未登录，不能写博客");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null || user.getId() <= 0){
            resp.getWriter().write("用户未登录，不能写博客");
            return;
        }
        Blog blog = new Blog();
        blog.setUserId(user.getId());
        blog.setTitle(title);
        blog.setContent(content);
        blogDao.insertBlog(blog);
        //返回博客列表页
        resp.sendRedirect("blog_list.html");
    }
}
